<template>
    <el-drawer :model-value="visible" :title="title" @close="closeDrawer" size="600px">
        <el-form ref="formRef" :model="detail" :rules="rules" label-width="120px">
            <el-row :gutter="10">
                <el-col :span="24">
                    <el-form-item prop="systemCode" label="所属业务系统">
                        <el-select v-model="detail.systemCode" clearable placeholder="请选择">
                            <template v-for="(item, index) in systemSelectList" :key="index">
                                <el-option :value="item.systemCode" :label="item.systemName"/>
                            </template>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="datasource" label="数据来源">
                        <el-input v-model.trim="detail.datasource" type="text" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="name" label="接口说明">
                        <el-input v-model.trim="detail.name" type="text" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="version" label="版本">
                        <el-input v-model.trim="detail.version" type="text" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="topic" label="主题">
                        <el-input v-model.trim="detail.topic" type="text" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="apiPath" label="接口路径">
                        <el-input v-model.trim="detail.apiPath" type="text" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="resultType" label="sql返回结果">
                        <el-select v-model="detail.resultType" clearable placeholder="请选择">
                            <template v-for="(item, index) in resultTypeSelectList" :key="index">
                                <el-option :value="item.value" :label="item.text"/>
                            </template>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="mybatisSql" label="MyBatis的执行sql">
                        <el-input v-model="detail.mybatisSql" type="textarea" :autosize="{ minRows: 5, maxRows: 100}" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="hasParams" label="是否有参数">
                        <el-input-number v-model="detail.hasParams" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="temporary" label="是否临时接口">
                        <el-input-number v-model="detail.temporary" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="expires" label="过期时间">
                        <el-date-picker v-model="detail.expires" type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm:ss"/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="cacheable" label="是否可以缓存">
                        <el-input-number v-model="detail.cacheable" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="cacheTime" label="缓存时长">
                        <el-input-number v-model="detail.cacheTime" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="remark" label="备注">
                        <el-input v-model="detail.remark" type="textarea" :autosize="{ minRows: 5, maxRows: 100}" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item>
                <el-button @click="save" type="primary" :icon="loading ? 'el-icon-loading' : 'el-icon-document'" :disabled="loading">保存</el-button>
                <el-button @click="closeDrawer" icon="el-icon-close">取消</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>

<script lang="ts">
import { ElNotification } from 'element-plus';
import { AxiosRequestConfig } from 'axios'
import { defineComponent, inject, reactive, ref, toRaw, toRefs, watch } from 'vue'
import { DataOperationType } from "@/constants"
import { copyProperties } from '@/utils/object-utils'
import { request } from '@/utils/request-utils'

const rules = {
    id: [{ type: 'integer', required: true, message: '接口ID不能为空', trigger: 'blur' }],
    systemCode: [{ required: true, message: '所属业务系统不能为空', trigger: 'change' }],
    datasource: [{ required: true, message: '数据来源不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '接口说明不能为空', trigger: 'blur' }],
}

const resultTypeSelectList = [
    { value: 1, text: 'List' }, 
    { value: 2, text: 'Object' }
]

export default defineComponent({
    emits: ['save'],
    props: {
        pk: {
            type: [Object, Map],
            required: false,
            default: () => undefined
        },
        operateType: {
            type: Number,
            default: () => DataOperationType.default
        },
        visible: {
            type: Boolean,
            default: () => false
        },
        systemSelectList: {
            type: Array,
            default: () => []
        }
    },
    setup(props, { emit }) {
        const { pk, operateType, visible } = toRefs(props)
        const title = ref<string>('')
        const loading = ref<boolean>(false)
        const formRef = ref()
        const detail = reactive<any>({
            id: undefined,
            systemCode: '',
            datasource: '',
            name: '',
            version: '',
            topic: '',
            apiPath: '',
            resultType: undefined,
            mybatisSql: '',
            hasParams: undefined,
            temporary: undefined,
            expires: '',
            cacheable: undefined,
            cacheTime: undefined,
            remark: '',
        })
        const resetForm = () => {
            formRef.value.resetFields()
            detail.id = undefined
            formRef.value.clearValidate()
        }
        const closeSaveDrawer = inject<(newVal: boolean) => void>('closeSaveDrawer')
        const closeDrawer = () => {
            resetForm()
            if (closeSaveDrawer) closeSaveDrawer(false)
        }

        const getDetail = (newVal: boolean) => {
            if (!newVal) return
            if (operateType.value === DataOperationType.default) return
            if (operateType.value === DataOperationType.create) {
                title.value = '添加接口配置'
            } else {
                if (operateType.value === DataOperationType.copy)
                    title.value = '复制接口配置'
                else if (operateType.value === DataOperationType.update)
                    title.value = '编辑接口配置'

                request({ url: '/api/detail', method: 'GET', params: pk.value }).then(response => {
                    if (operateType.value === DataOperationType.copy) {
                        copyProperties(response, detail, 'id')
                    } else {
                        copyProperties(response, detail)
                    }
                })
            }
        }

        watch(visible, getDetail)

        const save = () => {
            formRef.value.validate((valid: boolean) => {
                if (valid) {
                    loading.value = true;
                    const requestConfig: AxiosRequestConfig = operateType.value === DataOperationType.update
                        ? { url: '/api/update', method: "PATCH", data: toRaw(detail), params: pk.value }
                        : { url: '/api/add', method: "POST", data: toRaw(detail) }
                    request(requestConfig).then(response => {
                        ElNotification({
                            type: 'success',
                            message: "保存成功"
                        })
                        closeDrawer()
                        emit("save", response)
                    }).finally(() => {
                        loading.value = false
                    })
                } else {
                    ElNotification({
                        type: 'error',
                        message: "参数验证失败"
                    })
                    return false;
                }
            });
        }

        return {
            resultTypeSelectList,
            title, detail,
            formRef,
            rules,
            loading,
            save,
            closeDrawer
        }
    }
})
</script>

<style scoped>
</style>